package com.dmc.dmcPuzzle;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.Base64;
import android.util.Log;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;

/**
 * This class echoes a string called from JavaScript.
 */
public class Puzzle extends CordovaPlugin {

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("toPuzzle")) {
            this.toPuzzle(args, callbackContext);
            return true;
        }
        return false;
    }

    private void toPuzzle(JSONArray args, CallbackContext callbackContext) {
        try {
            String i1=args.getString(0);
            String i2=args.getString(1);
            Bitmap b1=stringtoBitmap(i1);
            Bitmap b2=stringtoBitmap(i2);
            float w1= stringtoBitmap(i1).getWidth();
            int h1=b1.getHeight();
            int h2=b2.getHeight();
            int w2=b2.getWidth();
            Bitmap result = Bitmap.createBitmap((int) w1, h1, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(result);
            canvas.drawBitmap(b1, 0, 0, null);
            float scale2=w1/w2;
            Matrix matrix = new Matrix();
            matrix.setScale(scale2,scale2);
            matrix.postTranslate(0,h1-scale2*h2);
            canvas.drawBitmap(b2,matrix, null);
            callbackContext.success(bitmaptoString(result,20));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将base64转换成bitmap图片
     *
     * @param string base64字符串
     * @return bitmap
     */

    public Bitmap stringtoBitmap(String string) {

// 将字符串转换成Bitmap类型

        Bitmap bitmap = null;

        try {

            byte[] bitmapArray;

            bitmapArray = Base64.decode(string, Base64.DEFAULT);

            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,

                    bitmapArray.length);

        } catch (Exception e) {

            e.printStackTrace();

        }

        return bitmap;

    }

    /**
     * 将bitmap转换成base64字符串
     *
     * @param bitmap
     * @return base64 字符串
     */

    public String bitmaptoString(Bitmap bitmap, int bitmapQuality) {



// 将Bitmap转换成字符串

        String string = null;

        ByteArrayOutputStream bStream = new ByteArrayOutputStream();

        bitmap.compress(Bitmap.CompressFormat.PNG, bitmapQuality, bStream);

        byte[] bytes = bStream.toByteArray();

        string = Base64.encodeToString(bytes, Base64.DEFAULT);

        return string;

    }
}
